package com.sgb.kjwl.view.widget.transport;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.kjwl.R;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.databinding.AppChooseMotorcadeDialogBinding;
import com.sgb.kjwl.model.entity.self.MotorcadeSimpleEntity;
import com.sgb.kjwl.model.entity.self.ProprietaryDriverEntity;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.ui.activity.transport.company.AddProprietaryFleetActivity;
import com.sgb.kjwl.view.ui.adapter.self.ChooseMotorcadeAdapter;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.event.EventConstant;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Describe:    选择车队的Dialog
 * Author:  yangLei
 * Date:    2021/10/12
 */
public class ChooseMotorcadeDialog extends Dialog implements View.OnClickListener {

    //0——编辑所属车队（修改自营司机车队时）     1——选择所属车队（添加自营司机时）     2——单纯选择车队，不需要请求接口
    private int type;
    private AppChooseMotorcadeDialogBinding mBinding;
    private Context mContext;
    private List<MotorcadeSimpleEntity> mMotorcades;
    private ChooseMotorcadeAdapter adapter;
    private MotorcadeSimpleEntity checkedEntity;
    private CheckResultListener resultListener;

    //所编辑的自营司机
    private ProprietaryDriverEntity driverInfo;
    private String title;


    private ChooseMotorcadeDialog(Context context, int windowType, List<MotorcadeSimpleEntity> motorcadeEntities) {
        super(context, R.style.app_transparent_dialog);
        this.type = windowType;
        this.mContext = context;
        this.mMotorcades = motorcadeEntities;
    }

    public static ChooseMotorcadeDialog newInstance(Context context, @IntRange(from = 0, to = 2) int windowType, List<MotorcadeSimpleEntity> motorcadeEntities) {
        return new ChooseMotorcadeDialog(context, windowType, motorcadeEntities);
    }

    public ProprietaryDriverEntity getDriverInfo() {
        return driverInfo;
    }

    public void setDriverInfo(ProprietaryDriverEntity driverInfo) {
        this.driverInfo = driverInfo;
        if (mBinding != null) {
            mBinding.driverInfo.setText(driverInfo.getNameAndPhoneNumber());
        }
    }

    public void setTitle(String title) {
        this.title = title;
        if (mBinding != null) {
            mBinding.titleTv.setText(title);
        }
    }

    public List<MotorcadeSimpleEntity> getMotorcadeEntities() {
        return mMotorcades;
    }

    public CheckResultListener getResultListener() {
        return resultListener;
    }

    public void setResultListener(CheckResultListener resultListener) {
        this.resultListener = resultListener;
    }

    public List<MotorcadeSimpleEntity> getMotorcades() {
        return mMotorcades;
    }

    public void setMotorcades(List<MotorcadeSimpleEntity> mMotorcades) {
        this.mMotorcades = mMotorcades;
        adapter.getData().clear();
        adapter.getData().addAll(mMotorcades);
        checkedEntity = null;
        if (mMotorcades != null && mMotorcades.size() > 0) {
            for (int i = 0; i < mMotorcades.size(); i++) {
                if (mMotorcades.get(i).isSelect()) {
                    checkedEntity = mMotorcades.get(i);
                }
            }
            switchListDisplay(true);
        } else {
            switchListDisplay(false);
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * 车队有无数据视图切换
     *
     * @param haveMotorcade 企业有无车队
     */
    private void switchListDisplay(boolean haveMotorcade) {
        if (haveMotorcade) {
            mBinding.motorcadeList.setVisibility(View.VISIBLE);
            if (type==1){
                mBinding.chooseHintTv.setVisibility(View.VISIBLE);
            }else {
                mBinding.chooseHintTv.setVisibility(View.GONE);
            }
            mBinding.nullListLayout.setVisibility(View.GONE);
        } else {
            mBinding.motorcadeList.setVisibility(View.GONE);
            mBinding.chooseHintTv.setVisibility(View.GONE);
            mBinding.nullListLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.app_choose_motorcade_dialog, null, false);
        setContentView(mBinding.getRoot());
        if (type == 0 || type == 2) {
            mBinding.chooseHintTv.setVisibility(View.GONE);
            mBinding.driverInfoLayout.setVisibility(View.GONE);
        } else if (type == 1) {
            mBinding.chooseHintTv.setVisibility(View.VISIBLE);
            mBinding.driverInfoLayout.setVisibility(View.VISIBLE);
        }

        if (mMotorcades == null) {
            mMotorcades = new ArrayList<>();
        }
        if (mMotorcades.size() < 1) {
            switchListDisplay(false);
        } else {
            switchListDisplay(true);
        }

        adapter = new ChooseMotorcadeAdapter(mMotorcades);
        mBinding.motorcadeList.setLayoutManager(new LinearLayoutManager(mContext));
        mBinding.motorcadeList.setAdapter(adapter);
        adapter.setOnItemChildClickListener((adapter, view, position) -> {
            itemChecked(position);
        });
        if (mMotorcades != null && mMotorcades.size() > 0) {
            for (int i = 0; i < mMotorcades.size(); i++) {
                if (mMotorcades.get(i).isSelect()) {
                    checkedEntity = mMotorcades.get(i);
                }
            }
        }

        mBinding.cancelBtn.setOnClickListener(this::onClick);
        mBinding.sureBtn.setOnClickListener(this::onClick);
        mBinding.addMotorcade.setOnClickListener(this::onClick);

        setCanceledOnTouchOutside(false);
    }

    private void itemChecked(int position) {
        if (mMotorcades.size() > position) {
            for (int i = 0; i < mMotorcades.size(); i++) {
                if (i == position) {
                    if (mMotorcades.get(position).isSelect()) {
                        mMotorcades.get(i).setSelect(false);
                        checkedEntity = null;
                    } else {
                        mMotorcades.get(i).setSelect(true);
                        checkedEntity = mMotorcades.get(position);
                    }
                } else {
                    mMotorcades.get(i).setSelect(false);
                }
            }
            this.adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel_btn:
                dismiss();
                break;

            case R.id.sure_btn:
                //可以不选择车队
                if (resultListener != null) {
                    request();
                }
                break;

            case R.id.add_Motorcade:
                dismiss();
                AddProprietaryFleetActivity.start(mContext, true);
                break;
        }
    }

    /**
     * 请求接口，进行司机移动分组或者添加分组
     */
    private void request() {
        if (type == 0 && driverInfo != null) {//编辑司机所属车队
            editBelongsTeam();
        } else if (type == 1 && driverInfo != null) {//新添加司机选择所属车队
            newAddDriver();
        } else if (type == 2) {//选择车队，不请求接口直接返回结果
            resultListener.onResult(checkedEntity);
        }
        dismiss();
    }

    /**
     * 编辑司机到指定车队车队
     */
    private void editBelongsTeam() {
        Map<String, Object> map = new HashMap<>();
        if (checkedEntity == null) {
            map.put("motorcadeNo", "");
            map.put("motorcadeName", "");
        } else {
            map.put("motorcadeNo", checkedEntity.getMotorcadeNo());
            map.put("motorcadeName", checkedEntity.getMotorcadeName());
        }
        map.put("driverNo", driverInfo.getDriverNo());
        NewAPIManager.getInstance().getLogisticsAPI().changeProDriverItem(map).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                EventBus.getDefault().postSticky(MenuEvent.make(EventConstant.EVENT_REFRESH_PRO_DRIVER, null));
                resultListener.onResult(checkedEntity);
                MToast.showToast(mContext, "编辑车队成功");
            }
        });
    }

    /**
     * 新添加司机到指定车队
     */
    private void newAddDriver() {
        Map<String, Object> map = new HashMap<>();
        if (checkedEntity == null) {
            map.put("motorcadeNo", "");
            map.put("motorcadeName", "");
        } else {
            map.put("motorcadeNo", checkedEntity.getMotorcadeNo());
            map.put("motorcadeName", checkedEntity.getMotorcadeName());
        }
        map.put("driverNo", driverInfo.getDriverNo());
        map.put("type", 1);
        NewAPIManager.getInstance().getLogisticsAPI().newAddProDriver(map).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                resultListener.onResult(checkedEntity);
                EventBus.getDefault().postSticky(MenuEvent.make(EventConstant.EVENT_REFRESH_PRO_DRIVER, null));
                MToast.showToast(mContext, "添加成功");
            }
        });
    }

    /**
     * 根据当前所在车队设置默认选中项
     *
     * @param entities 源数据
     * @param no       所在车队的No
     * @return
     */
    public static List<MotorcadeSimpleEntity> setDefaultItem(@NonNull List<MotorcadeSimpleEntity> entities, String no) {
        if (entities.size() > 0) {
            for (int i = 0; i < entities.size(); i++) {
                if (!TextUtils.isEmpty(no) && !TextUtils.isEmpty(entities.get(i).getMotorcadeNo()) && entities.get(i).getMotorcadeNo().equals(no)) {
                    entities.get(i).setSelect(true);
                } else {
                    entities.get(i).setSelect(false);
                }
            }
        }
        return entities;
    }

    public interface CheckResultListener {
        void onResult(MotorcadeSimpleEntity entity);
    }
}
